package com.kb.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池配置
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig {

    @Bean("componentExecutor")
    public ThreadPoolExecutor componentExecutor() {
        // 获取当前服务器的CPU核心数
        int cpuCoreCount = Math.min(Runtime.getRuntime().availableProcessors(), 5);

        // 核心线程数 = CPU核心数 * 2（可根据实际情况调整倍数）
        int corePoolSize = cpuCoreCount * 4;
        // 最大线程数 = CPU核心数 * 4（可根据实际情况调整倍数）
        int maximumPoolSize = cpuCoreCount * 8;

        return new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                60,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(50),
                r -> new Thread(r, "component-thread:" + r.hashCode()),
                new ThreadPoolExecutor.CallerRunsPolicy());
    }

}